package com.example.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManager {
    private ConcurrentHashMap<Integer, WebSocketSession> sessions=new ConcurrentHashMap<>();

    public void oline(int userId,WebSocketSession session){
        if(sessions.get(userId)!=null){
//            用户已经上线
            return;
        }
        sessions.put(userId,session);
        System.out.println("["+userId+"]上线!");
    }

    public void offline(int userId,WebSocketSession session){
        WebSocketSession existSession=sessions.get(userId);
        if(existSession!=session){
//            当前调用离线的时候的会话不是之前存储的会话,不产生实际效果.
            return;
        }
        sessions.remove(userId);
        System.out.println("["+userId+"]下线!");
    }

    public WebSocketSession getSession(int userId){
        return sessions.get(userId);
    }
}
